package com.sysmanage.permissions.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import com.sysmanage.common.tools.page.Pagination;
import com.sysmanage.framework.dao.hibernate.Finder;
import com.sysmanage.framework.dao.hspring.BaseDAO;
import com.sysmanage.permissions.ConstCode;
import com.sysmanage.permissions.model.Department;
import com.sysmanage.permissions.model.Groups;
import com.sysmanage.permissions.model.Role;
import com.sysmanage.permissions.model.Systems;
import com.sysmanage.permissions.model.Users;

/** 
  * @ClassName: UsersDao 
  * @Description: 用户Dao层
  * @author XXXX@163.com
  * @date 2011-9-26 上午9:58:14 
  *  
  */
@Repository(value="userDao")
public class UsersDao extends BaseDAO<Users> {
	/** 
	  * @Title: getAll 
	  * @Description: 获取所有的用户
	  * @param @return
	  * @return List<Users>
	  * @throws 
	  */
	public List<Users> getAll(){
		StringBuffer sb = new StringBuffer("from Users");
		return this.getHandler().findListOfObj(sb.toString());
	}

	/** 
	  * @Title: getGroupAll 
	  * @Description: 获取某组下的所有用户
	  * @param @param groupId
	  * @param @return
	  * @return List<Users>
	  * @throws 
	  */
	public List<Users> getGroupAll(Integer groupId) {
		List<Users> result = null;
		StringBuffer sb = new StringBuffer("from Groups where id=" + groupId + " or parentId=" + groupId);		
		List<Groups> groups = this.getHandler().findListOfObj(sb.toString());
		
		Set<Users> users = new HashSet<Users>();
		
		if(null != groups  && groups.size() > 0){
			result = new ArrayList<Users>();
			for(int i=0;i<groups.size();i++){
				Groups group = groups.get(i);
				Set<Users> set = group.getUsers();
				Iterator<Users> it = set.iterator();
				while(it.hasNext()){
					users.add(it.next());
				}
			}
		}
		
		Iterator<Users> it= users.iterator();
		while(it.hasNext()){
			result.add(it.next());
		}
		
		return result;
	}
	/** 
	  * @Title: getGroupAllPageList 
	  * @Description: 具体某页显示多少条记录
	  * @param @param groupId 组id
	  * @param @param page 当前页
	  * @param @param rows 一页显示多少条记录
	  * @param @return
	  * @return Pagination
	  * @throws 
	  */
	public Pagination getGroupAllPageList(Integer groupId, int page, int rows,String sort,String order) {
		StringBuffer sb = new StringBuffer("from Users where 1=1");
		if(null != groupId){			
			sb.append(" and id in (select userId from UserGroup where groupId=" +groupId + ")");					
		}
		sb.append(" order by deptId");
		try{
		return super.getHandler().getPageList(Finder.create(sb.toString()), page, rows);
		}catch(Exception ex)
		{
			ex.printStackTrace();
			return null;
		}
	}
	/** 
	  * @Title: getGroupOtherPageList 
	  * @Description: 具体某页显示多少条记录
	  * @param @param groupId 组id
	  * @param @param user 一条具体的用户信息
	  * @param @param page 当前页
	  * @param @param rows 一页显示多少条记录
	  * @param @return
	  * @return Pagination
	  * @throws 
	  */
	public Pagination getGroupOtherPageList(Integer groupId,Users user, int page, int rows,String sort,String order) {
		StringBuffer sb = new StringBuffer("from Users where 1=1");
		if(null != groupId){			
			sb.append(" and id not in (select userId from UserGroup where groupId=" +groupId + ")");					
		}
		if(null != user){
			if(null !=user.getLogonid() && !"".equals(user.getLogonid())){
				sb.append(" and logonid like'%" + user.getLogonid() + "%'");
			}
			if(null !=user.getUsertype() && !"".equals(user.getUsertype())&& !"-1".equals(user.getUsertype())){
				sb.append(" and usertype ='" + user.getUsertype() + "'");
			}
			if(null !=user.getStatus() && user.getStatus()>=0){
				sb.append(" and status ='" + user.getStatus() + "'");
			}
			if(null != user.getName() && !"".equals(user.getName())){
				sb.append(" and name like'%" + user.getName() + "%'");
			}
			if(null != user.getEnname() && !"".equals(user.getEnname())){
				sb.append(" and enname like'%" + user.getEnname() + "%'");
			}
			if(null != user.getCompanyId() && user.getCompanyId()>0){
				sb.append(" and companyId =" + user.getCompanyId() + "");
			}
		}
		if(sort!=null && !"".equals(sort)){
			sb.append(" order by "+sort);
			if(order!=null && !"".equals(order)){
				sb.append(" "+order);
			}else{
				sb.append(" desc");
			}
		}
		else
		{
			sb.append(" order by deptId");
		}
		//sb.append(" order by registerdate desc");
		try{
		return super.getHandler().getPageList(Finder.create(sb.toString()), page, rows);
		}catch(Exception ex)
		{
			ex.printStackTrace();
			return null;
		}
	}	
	/**
	 * 获取部门用户树
	 * @param 部门ID
	 * @return
	 */	
	public List<Map<String,Object>> getDeptUserTree(String deptId){
		List<Map<String,Object>> nodes = new ArrayList<Map<String,Object>>();
		//存放每层资源的临时变量
		List<Map<String,Object>> temp = new ArrayList<Map<String,Object>>();
		//第一级资源
		String hsql = "from Department where parentId is null";
		if(deptId!=null&&deptId.trim()!=null)
		{
			hsql = "from Department where parentId =" + deptId;
		}				
		List<Department> types  =  this.getHandler().findListOfObj(hsql);
		if(null == types || types.size() == 0){
			return nodes;
		}
		for(Department type: types){
				Map<String,Object> node = new HashMap<String,Object>();
				node.put("id",  "D"+type.getId()+"");
				node.put("text", "部门_"+type.getDeptName());
				nodes.add(node);
				//temp.add(node);
		}
		//临时
		List<Map<String,Object>> doing = new ArrayList<Map<String,Object>>();
		doing.addAll(nodes);
		
		//获取该部门的用户
		List<Object> nullNode = new ArrayList<Object>();
		if(deptId!=null&&deptId.trim()!=null)
		{		
			List<Users> users  =  this.getHandler().findListOfObj("from Users where deptId="+deptId);
			if(null != users || users.size() > 0)
			{
				
				for(Users type: users){
						Map<String,Object> node = new HashMap<String,Object>();
						node.put("id",  type.getId()+"");
						node.put("text", type.getName());
						node.put("children", nullNode.toArray(new Object[nullNode.size()]));
						nodes.add(node);
				}
			}
		}
		
		while(!doing.isEmpty()){
			temp = new ArrayList<Map<String,Object>>();
			for(Map<String,Object> item: doing){
				List<Object> children = new ArrayList<Object>();
				String pid = (String)item.get("id");
				List<Department> tempTypes  =  this.getHandler().findListOfObj("from Department where parentId=" + pid.substring(1));
				for(Department type: tempTypes){
					Map<String,Object> node = new HashMap<String,Object>();
					node.put("id",  "D"+type.getId()+"");
					node.put("text", "部门_"+type.getDeptName());
					temp.add(node);
					children.add(node);
				}
				List<Users> users  =  this.getHandler().findListOfObj("from Users where deptId="+pid.substring(1));
				for(Users type: users){
					Map<String,Object> node = new HashMap<String,Object>();
					node.put("id",  type.getId()+"");
					node.put("text", type.getName());
					node.put("children", nullNode.toArray(new Object[nullNode.size()]));
					children.add(node);
			}				
				
				item.put("children", children.toArray(new Object[children.size()]));
			}
			doing = temp;
		}

		return nodes;
	}	
	/** 
	  * @Title: getPageList 
	  * @Description: 具体某页显示多少条记录
	  * @param @param user 一条具体的用户信息
	  * @param @param page 当前页
	  * @param @param rows 一页显示多少条记录
	  * @param @return
	  * @return Pagination
	  * @throws 
	  */
	public Pagination getPageList(Users user, int page, int rows,String sort,String order) {
		StringBuffer sb = new StringBuffer("from Users where 1=1");
		if(null != user){
			if(null !=user.getLogonid() && !"".equals(user.getLogonid())){
				sb.append(" and logonid like'%" + user.getLogonid() + "%'");
			}
			if(null !=user.getUsertype() && !"".equals(user.getUsertype())&& !"-1".equals(user.getUsertype())){
				sb.append(" and usertype ='" + user.getUsertype() + "'");
			}
			if(null !=user.getStatus() && user.getStatus()>=0){
				sb.append(" and status ='" + user.getStatus() + "'");
			}
			
			if(null != user.getName() && !"".equals(user.getName())){
				sb.append(" and name like'%" + user.getName() + "%'");
			}
			if(null != user.getEnname() && !"".equals(user.getEnname())){
				sb.append(" and enname like'%" + user.getEnname() + "%'");
			}
			if(null != user.getDeptId() && user.getDeptId()>0){
				sb.append(" and deptId =" + user.getDeptId());
			}
			if(null != user.getCompanyId() && user.getCompanyId()>0){
				sb.append(" and companyId =" + user.getCompanyId());
			}
		}
		if(sort!=null && !"".equals(sort)){
			sb.append(" order by "+sort);
			if(order!=null && !"".equals(order)){
				sb.append(" "+order);
			}else{
				sb.append(" desc");
			}
		}
		else
		{
			sb.append(" order by logonid");
		}
		return super.getHandler().getPageList(Finder.create(sb.toString()), page, rows);
	}
	
	/** 
	  * @Title: saveToGroup 
	  * @Description: 往组里面添加用户
	  * @param @param groupId 组id
	  * @param @param user 具体用户信息
	  * @param @return
	  * @return Boolean
	  * @throws 
	  */
	public Boolean saveToGroup(String groupId, Users user){
		Boolean flag = false;
		try {
			Groups group = (Groups)this.getHandler().findObjById(Groups.class, Integer.valueOf(groupId));
			Set<Users> set = group.getUsers();
			this.getHandler().saveObj(user);
			set.add(user);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}

	/** 
	  * @Title: login 
	  * @Description: 验证用户名和密码 
	  * @param  userName
	  * @param  password
	  * @return Users 验证成功返回Users对象，失败返回null
	  * @throws 
	  * @author XXXX@163.com
	  */
	public Users login(String userName,String password){
		return (Users) this.getHandler().findObj("from Users where logonid ="+"'"+userName+"'"+" and password="+"'"+password+"' and status='"+ConstCode.STATUS_ENABLE+"'");
	}

	/** 
	  * @Title: returnGroupName 
	  * @Description: TODO(这里用一句话描述这个方法的作用) 
	  * @param @param userId
	  * @param @return
	  * @return String
	  * @throws 
	  */
	public String returnRoleName(String userId) {
		Users user = (Users)this.getHandler().findObj("from Users where logonid ='" + userId + "'");
		Set<Groups> sets = user.getGroups();
		StringBuffer sb = new StringBuffer("");
		/*
		 * 这是按一个用户只能有一个组,来设计的
		 */
		Iterator<Groups> it = sets.iterator();
		while(it.hasNext()){
			Groups group = it.next();
			
			Set<Role> roles = group.getRoles();
			Iterator<Role> temp = roles.iterator();
			while(temp.hasNext()){
				sb.append("," + temp.next().getEnname());
			}
		}
		
		return sb.toString();
	}

	/** 
	  * @Title: alterToGroup 
	  * @Description: TODO(这里用一句话描述这个方法的作用) 
	  * @param @param user
	  * @param @param groupId
	  * @param @return
	  * @return boolean
	  * @throws 
	  */
	public boolean alterToGroup(Users user, String groupId) {
		Set<Groups> set = new HashSet<Groups>(); 
		set.add((Groups)this.getHandler().findObj("from Groups where id=" + groupId + ""));
		if(this.getHandler().alterObj(user)){
			user.setGroups(set);
			return true;
		}
		
		return false;
	}
	public List<Users> findByLoginIds(String ids){
		String[] strs=ids.split(",");
		List<Users> list=new ArrayList<Users>();
		for(int i=0;i<strs.length;i++){
			Users user=new Users();
			user=(Users) this.getHandler().findObj("from Users where logonid ='" + strs[i] + "'");
			list.add(user);
		}
		return list;
	}
	public List<Users> findByName(String name){
		List<Users> list  =  this.getHandler().findListOfObj("from Users where name like '%"+name+"%' or logonid like '%"+name+"%'");
		return list;
	}
	public List<Users> getAllValidUser(){
		List<Users> list  =  this.getHandler().findListOfObj("from Users where status='1'");
		return list;
	}
	public List<Users> findByCompanyId(Integer companyId){
		List<Users> list  =  this.getHandler().findListOfObj("from Users where companyId ="+companyId);
		return list;
	}	
}
